<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定位管理后台</title>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .header h1 {
            color: #667eea;
            font-size: 32px;
            margin-bottom: 10px;
        }
        
        .status {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }
        
        .status.connected {
            background: #10b981;
            color: white;
        }
        
        .status.disconnected {
            background: #ef4444;
            color: white;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .card h2 {
            color: #333;
            font-size: 24px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 3px solid #667eea;
        }
        
        .device-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .device-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #667eea;
            transition: all 0.3s;
        }
        
        .device-item:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .device-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .device-name {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
        
        .device-id {
            font-size: 12px;
            color: #666;
            font-family: monospace;
        }
        
        .device-info {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-size: 14px;
            color: #333;
            font-weight: 500;
        }
        
        .location-info {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-top: 10px;
        }
        
        .location-coords {
            font-family: monospace;
            font-size: 14px;
            color: #667eea;
            margin-bottom: 8px;
        }
        
        .location-address {
            font-size: 13px;
            color: #555;
            line-height: 1.5;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 10px;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .map-view {
            height: 600px;
        }
        
        #map {
            width: 100%;
            height: 500px;
            border-radius: 10px;
            margin-top: 15px;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        .empty-state svg {
            width: 100px;
            height: 100px;
            margin-bottom: 20px;
            opacity: 0.3;
        }
        
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            margin-left: 10px;
        }
        
        .badge-success {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-warning {
            background: #fef3c7;
            color: #92400e;
        }
        
        .log-container {
            max-height: 300px;
            overflow-y: auto;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            font-family: monospace;
            font-size: 13px;
        }
        
        .log-entry {
            padding: 8px;
            margin-bottom: 5px;
            border-left: 3px solid #667eea;
            padding-left: 12px;
        }
        
        .log-entry.info {
            border-left-color: #3b82f6;
            background: #eff6ff;
        }
        
        .log-entry.success {
            border-left-color: #10b981;
            background: #d1fae5;
        }
        
        .log-entry.warning {
            border-left-color: #f59e0b;
            background: #fef3c7;
        }
        
        .log-time {
            color: #666;
            margin-right: 10px;
        }
        
        @media (max-width: 1024px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📍 定位管理后台</h1>
            <p>实时监控和管理设备位置</p>
            <div style="margin-top: 15px;">
                <span id="connection-status" class="status disconnected">未连接</span>
                <span style="margin-left: 15px; color: #666;">在线设备: <strong id="device-count">0</strong></span>
            </div>
        </div>
        
        <div class="main-content">
            <div class="card">
                <h2>📱 连接设备</h2>
                <div id="device-list" class="device-list">
                    <div class="empty-state">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                        </svg>
                        <p>暂无连接的设备</p>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h2>📋 操作日志</h2>
                <div id="log-container" class="log-container"></div>
            </div>
        </div>
    </div>

    <script>
        // 连接到WebSocket服务器
        const socket = io();
        
        let devices = {};
        const logs = [];
        
        // 添加日志
        function addLog(message, type = 'info') {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('zh-CN');
            logs.unshift({ time: timeStr, message, type });
            if (logs.length > 50) logs.pop();
            updateLogDisplay();
        }
        
        // 更新日志显示
        function updateLogDisplay() {
            const container = document.getElementById('log-container');
            container.innerHTML = logs.map(log => `
                <div class="log-entry ${log.type}">
                    <span class="log-time">${log.time}</span>
                    <span>${log.message}</span>
                </div>
            `).join('');
        }
        
        // 更新设备列表显示
        function updateDeviceList() {
            const container = document.getElementById('device-list');
            const deviceArray = Object.values(devices);
            
            document.getElementById('device-count').textContent = deviceArray.length;
            
            if (deviceArray.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
                        </svg>
                        <p>暂无连接的设备</p>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = deviceArray.map(device => {
                const location = device.location;
                const hasLocation = location && location.latitude && location.longitude;
                
                return `
                    <div class="device-item">
                        <div class="device-header">
                            <div>
                                <div class="device-name">
                                    ${device.device_name}
                                    ${hasLocation ? (location.is_simulated ? 
                                        '<span class="badge badge-warning">模拟</span>' : 
                                        '<span class="badge badge-success">真实</span>') : ''}
                                </div>
                                <div class="device-id">ID: ${device.device_id.substring(0, 16)}...</div>
                            </div>
                        </div>
                        
                        <div class="device-info">
                            <div class="info-item">
                                <div class="info-label">连接时间</div>
                                <div class="info-value">${new Date(device.connected_at).toLocaleString('zh-CN')}</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">最后更新</div>
                                <div class="info-value">${new Date(device.last_update).toLocaleString('zh-CN')}</div>
                            </div>
                        </div>
                        
                        ${hasLocation ? `
                            <div class="location-info">
                                <div class="location-coords">
                                    📍 ${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)}
                                    (精度: ${location.accuracy}m)
                                </div>
                                ${location.address ? `
                                    <div class="location-address">
                                        ${location.location_name ? `<strong>${location.location_name}</strong><br>` : ''}
                                        ${location.address}
                                    </div>
                                ` : ''}
                            </div>
                        ` : '<div class="location-info">暂无位置信息</div>'}
                        
                        <div style="margin-top: 15px;">
                            <button class="btn btn-primary" onclick="requestLocation('${device.device_id}')">
                                📡 请求定位
                            </button>
                            <button class="btn btn-secondary" onclick="viewHistory('${device.device_id}')">
                                📜 查看历史
                            </button>
                        </div>
                    </div>
                `;
            }).join('');
        }
        
        // 请求设备上报位置
        function requestLocation(deviceId) {
            fetch(`/api/device/${deviceId}/request-location`, {
                method: 'POST'
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    addLog(`已向设备发送定位请求`, 'info');
                } else {
                    addLog(`发送定位请求失败: ${data.error}`, 'warning');
                }
            })
            .catch(err => {
                addLog(`请求失败: ${err.message}`, 'warning');
            });
        }
        
        // 查看设备历史
        function viewHistory(deviceId) {
            fetch(`/api/device/${deviceId}/history`)
                .then(res => res.json())
                .then(data => {
                    const count = data.history.length;
                    addLog(`设备有 ${count} 条历史记录`, 'info');
                    if (count > 0) {
                        const latest = data.history[count - 1];
                        addLog(`最新位置: (${latest.latitude}, ${latest.longitude})`, 'success');
                    }
                });
        }
        
        // WebSocket事件监听
        socket.on('connect', () => {
            document.getElementById('connection-status').className = 'status connected';
            document.getElementById('connection-status').textContent = '已连接';
            addLog('WebSocket连接成功', 'success');
            
            // 获取设备列表
            fetch('/api/devices')
                .then(res => res.json())
                .then(data => {
                    data.devices.forEach(device => {
                        devices[device.device_id] = device;
                    });
                    updateDeviceList();
                });
        });
        
        socket.on('disconnect', () => {
            document.getElementById('connection-status').className = 'status disconnected';
            document.getElementById('connection-status').textContent = '未连接';
            addLog('WebSocket连接断开', 'warning');
        });
        
        socket.on('device_connected', (data) => {
            addLog(`设备上线: ${data.device_name}`, 'success');
            devices[data.device_id] = {
                device_id: data.device_id,
                device_name: data.device_name,
                connected_at: data.timestamp,
                last_update: data.timestamp
            };
            updateDeviceList();
        });
        
        socket.on('location_update', (data) => {
            addLog(`收到位置上报: ${data.device_name} (${data.location.latitude.toFixed(6)}, ${data.location.longitude.toFixed(6)})`, 'success');
            
            if (devices[data.device_id]) {
                devices[data.device_id].location = data.location;
                devices[data.device_id].last_update = new Date().toISOString();
                updateDeviceList();
            }
        });
        
        // 初始化
        addLog('管理后台已启动', 'info');
    </script>
</body>
</html>

